package models

import (
	"fmt"
	"time"
	_ "time"

	"go-papers/cache"
	orm "go-papers/database"
	"go-papers/tools"
)

type MemberContrast struct {
	ContrastId     int    `json:"contrastId" gorm:"type:int(11) unsigned;primary_key"` //
	MemberId       int    `json:"memberId" gorm:"type:int(11);"`                       // 用户id
	CourseId       int    `json:"courseId" gorm:"type:int(11);"`                       // 课程id
	CourseName     string `json:"courseName" gorm:"type:varchar(255);"`                // 课程名称
	ContrastStatus string `json:"contrastStatus" gorm:"type:varchar(2);"`              // 课程名称
	ThirdUserId    int    `json:"thirdUserId" gorm:"type:int(11);"`                    // 用户第三方账户 id

	OrganFeature string `json:"organFeature" gorm:"-"` // 课程名称

	CourseType     string `json:"courseType"  gorm:"-"`     // 课程类目 课程类别  素质教育
	CourseCategory string `json:"courseCategory"  gorm:"-"` // 学科科目 语文/数学

	OrganId      int    `json:"organId"  gorm:"-"`      // 授课机构
	OrganBrandId int    `json:"organBrandId"  gorm:"-"` // 授课机构
	OrganName    string `json:"organName"  gorm:"-"`    // 机构名称
	CourseTeach  string `json:"courseTeach"  gorm:"-"`  // 授课方式 ：线上 、 线下

	CourseExpensive string `json:"courseExpensive"  gorm:"-"` // 是否 贵就赔 1 是 / 0 否

	CoursePrice   float64 `json:"coursePrice"  gorm:"-"`   // 授课金额
	DiscountPrice float64 `json:"discountPrice"  gorm:"-"` // 优惠金额

	CourseTime string `json:"courseTime"  gorm:"-"` // 授课时间 字符串
	CourseAge  string `json:"courseAge"  gorm:"-"`  // 授课适合年龄 1 :0～3岁 3 :3～6岁 6 :7-12岁 9:12-18岁  12: 18岁+

	CourseVideo    string `json:"courseVideo"  gorm:"-"`    // 介绍视频 json
	CourseImg      string `json:"courseImg"  gorm:"-"`      // 介绍图片 json
	CourseSystem   string `json:"courseSystem"  gorm:"-"`   // 课程体系
	CourseFeature  string `json:"courseFeature"  gorm:"-"`  // 课程特色
	CourseTools    string `json:"courseTools"  gorm:"-"`    // 课程教具
	CourseService  string `json:"courseService"  gorm:"-"`  // 课程服务体系
	CourseTransfer string `json:"courseTransfer"  gorm:"-"` // 支付转让
	CourseFree     string `json:"courseFree"  gorm:"-"`     // 支付冻结
	CourseRefund   string `json:"courseRefund"  gorm:"-"`   // 退费规则
	CourseLeave    string `json:"courseLeave" gorm:"-"`     // 请假制度

	CourseInfo interface{} `json:"courseInfo"  gorm:"-"` // 介绍详情
	OrganInfo  interface{} `json:"organInfo"  gorm:"-"`  // 介绍详情
	BrandInfo  interface{} `json:"brandInfo"  gorm:"-"`  // 介绍详情

	CourseStatus string `json:"courseStatus"  gorm:"-"` // 核准状态 1 待审核 ，3 失败 ， 5 已审核

	DataScope string `json:"dataScope" gorm:"-"`
	Params    string `json:"params"  gorm:"-"`
	OpenId    string `json:"openId"  gorm:"-"`
	Token     string `json:"token"  gorm:"-"`

	CompareInfo map[string]interface{} `json:"compareInfo" gorm:"-"`

	BaseModel
}

func (MemberContrast) TableName() string {
	return "member_contrast"
}

// 创建MemberContrast
func (e *MemberContrast) Create() (MemberContrast, error) {
	var doc MemberContrast
	result := orm.Eloquent.Table(e.TableName()).Create(&e)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}
	doc = *e
	return doc, nil
}

// GetV2
func (e *MemberContrast) GetV2() (MemberContrast, error) {
	var doc MemberContrast
	table := orm.Eloquent.Select("*, course.*,organ.organ_feature").Table(e.TableName())
	table = table.Joins("inner join course on course.course_id = member_contrast.course_id ")
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id ")
	if e.ContrastId != 0 {
		table = table.Where("`member_contrast`.contrast_id = ?", e.ContrastId)
	}
	if e.MemberId != 0 {
		table = table.Where("`member_contrast`.member_id = ?", e.MemberId)
	} else if e.ThirdUserId != 0 {
		table = table.Where("`member_contrast`.third_user_id = ?", e.ThirdUserId)
	}
	if e.CourseId != 0 {
		table = table.Where("`member_contrast`.course_id = ?", e.CourseId)
	}
	if e.ContrastStatus != "" {
		table = table.Where("`member_contrast`.contrast_status = ?", e.ContrastStatus)
	}
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 获取MemberContrast
func (e *MemberContrast) Get() (MemberContrast, error) {
	var doc MemberContrast
	table := orm.Eloquent.Select("*, course.*").Table(e.TableName())
	table = table.Joins("inner join course on course.course_id = member_contrast.course_id ")

	if e.ContrastId != 0 {
		table = table.Where("`member_contrast`.contrast_id = ?", e.ContrastId)
	}
	if e.MemberId != 0 {
		table = table.Where("`member_contrast`.member_id = ?", e.MemberId)
	}
	if e.CourseId != 0 {
		table = table.Where("`member_contrast`.course_id = ?", e.CourseId)
	}
	if e.CourseName != "" {
		table = table.Where("`member_contrast`.course_name = ?", e.CourseName)
	}
	if e.ContrastStatus != "" {
		table = table.Where("`member_contrast`.contrast_status = ?", e.ContrastStatus)
	}
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// BatchGetBrandNameV2
func (e *MemberContrast) BatchGetBrandNameV2(ids []int) (map[int]MemberContrast, error) {
	var doc []MemberContrast

	table := orm.Eloquent.Select("`member_contrast`.course_id , `member_contrast`.contrast_status , `course`.*").Table(e.TableName())
	table = table.Joins("inner join course on course.course_id = member_contrast.course_id ")

	if e.MemberId != 0 {
		table = table.Where("`member_contrast`.member_id = ?", e.MemberId)
	} else if e.ThirdUserId != 0 {
		table = table.Where("`member_contrast`.third_user_id = ?", e.ThirdUserId)
	}

	table = table.Where("`member_contrast`.course_id in (?)", ids)

	if err := table.Order(" `member_contrast`.`contrast_id`  DESC", true).Find(&doc).Error; err != nil {
		return nil, err
	}
	info := make(map[int]MemberContrast, 0)
	if len(doc) > 0 {
		for _, v := range doc {
			info[v.CourseId] = v
		}
		return info, nil
	}
	return info, nil
}

func (e *MemberContrast) GetComparePage() ([]MemberContrast, int, error) {
	var doc []MemberContrast

	table := orm.Eloquent.Select("`member_contrast`.*,`course`.*").Table(e.TableName())
	table = table.Joins("inner join course on course.course_id = member_contrast.course_id ")

	if e.ContrastId != 0 {
		table = table.Where("`member_contrast`.contrast_id = ?", e.ContrastId)
	}
	if e.MemberId != 0 {
		table = table.Where("`member_contrast`.member_id = ?", e.MemberId)
	} else if e.ThirdUserId != 0 {
		table = table.Where("`member_contrast`.third_user_id = ?", e.ThirdUserId)
	}
	if e.CourseId != 0 {
		table = table.Where("`member_contrast`.course_id = ?", e.CourseId)
	}
	if e.ContrastStatus != "" {
		table = table.Where("`member_contrast`.contrast_status = ?", e.ContrastStatus)
	}

	var count int

	if err := table.Order(" `member_contrast`.`contrast_id`  DESC", true).Find(&doc).Error; err != nil {
		return nil, 0, err
	}

	table.Where("`member_contrast`.`deleted_at` IS NULL").Count(&count)

	if len(doc) > 0 {
		var organ Organ
		var cc Course
		var bb OrganBrand
		for i := 0; i < len(doc); i++ {
			//随机对比
			doc[i].CompareInfo = getCompareInfo(doc[i].CourseId)

			courseInfo, _ := cc.GetById(doc[i].CourseId)
			doc[i].CourseInfo = courseInfo

			organInfo, _ := organ.GetByID(courseInfo.OrganId)
			doc[i].OrganInfo = organInfo

			brandInfo, _ := bb.GetByID(organInfo.OrganBrandId)
			doc[i].BrandInfo = brandInfo

		}
	}

	return doc, count, nil
}

// 获取MemberContrast带分页
func (e *MemberContrast) GetPage(pageSize int, pageIndex int) ([]MemberContrast, int, error) {
	var doc []MemberContrast

	table := orm.Eloquent.Select("*, course.*,organ.organ_feature").Table(e.TableName())
	table = table.Joins("inner join course on course.course_id = member_contrast.course_id ")
	table = table.Joins("inner join organ on  `organ`.organ_id = course.organ_id ")

	if e.ContrastId != 0 {
		table = table.Where("`member_contrast`.contrast_id = ?", e.ContrastId)
	}
	if e.MemberId != 0 {
		table = table.Where("`member_contrast`.member_id = ?", e.MemberId)
	} else if e.ThirdUserId != 0 {
		table = table.Where("`member_contrast`.third_user_id = ?", e.ThirdUserId)
	}
	if e.CourseId != 0 {
		table = table.Where("`member_contrast`.course_id = ?", e.CourseId)
	}
	if e.ContrastStatus != "" {
		table = table.Where("`member_contrast`.contrast_status = ?", e.ContrastStatus)
	}
	if e.CourseName != "" {
		table = table.Where("`course`.course_name like ?", "%"+e.CourseName+"%")
	}
	var count int

	if err := table.Order(" `member_contrast`.`contrast_id`  DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("`member_contrast`.`deleted_at` IS NULL").Count(&count)

	if len(doc) > 0 {
		var organ Organ

		var bb OrganBrand
		for i := 0; i < len(doc); i++ {
			//随机对比
			doc[i].CompareInfo = getCompareInfo(doc[i].CourseId)

			organInfo, _ := organ.GetByID(doc[i].OrganId)
			doc[i].OrganInfo = organInfo

			brandInfo, _ := bb.GetByID(organInfo.OrganBrandId)
			doc[i].BrandInfo = brandInfo

		}
	}

	return doc, count, nil
}

// 课程 多维度对比 参数对比
// A  // 价格
// B  // 平台销量
// C // 退费率
// D // 优惠
// E // 续课率
func getCompareInfo(id int) map[string]interface{} {

	// cache 中 获取
	//cache 读取 然后返回
	cacheKey := fmt.Sprintf("course:compare:%d", id)
	if foo, ok := cache.GoLocalCache.Get(cacheKey); ok {
		l, _ := foo.(map[string]interface{})
		return l
	}
	//虚拟
	a := float64(tools.RandInt(70, 85)) / 10.0 // 价格
	b := float64(tools.RandInt(80, 85)) / 10.0 // 平台销量
	c := float64(tools.RandInt(0, 2)) / 10.0   // 退费率
	d := float64(tools.RandInt(70, 80)) / 10.0 // 优惠
	e := float64(tools.RandInt(80, 90)) / 10.0 // 续课率

	out := map[string]interface{}{
		"A": fmt.Sprintf("%.1f", a), // 价格
		"B": fmt.Sprintf("%.1f", b), // 平台销量
		"C": fmt.Sprintf("%.1f", c), // 退费率
		"D": fmt.Sprintf("%.1f", d), // 优惠
		"E": fmt.Sprintf("%.1f", e), // 续课率
	}

	// 写入cache
	cache.GoLocalCache.Set(cacheKey, out, 30*time.Minute)

	return out
}

// 更新MemberContrast
func (e *MemberContrast) Update(id int) (update MemberContrast, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("contrast_id = ?", id).First(&update).Error; err != nil {
		return
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

// UpdateStatus
func (e *MemberContrast) BatchUpdateStatus(id []int, status string) (Result bool, err error) {

	table := orm.Eloquent.Table(e.TableName())
	sql := " UPDATE member_contrast SET contrast_status = " + status + " WHERE contrast_id in (?) "
	if e.MemberId != 0 {
		sql += " AND member_id = " + tools.IntToString(e.MemberId) + " "
	} else if e.ThirdUserId != 0 {
		sql += " AND third_user_id = " + tools.IntToString(e.ThirdUserId) + " "
	}
	if err = table.Exec(sql, id).Error; err != nil {
		return
	}
	Result = true
	return
}

// 删除MemberContrast
func (e *MemberContrast) Delete(id int) (success bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("contrast_id = ?", id).Delete(&MemberContrast{}).Error; err != nil {
		success = false
		return
	}
	success = true
	return
}

//批量删除
func (e *MemberContrast) BatchDelete(id []int) (Result bool, err error) {
	table := orm.Eloquent.Table(e.TableName())
	sql := " DELETE FROM `member_contrast`  WHERE contrast_id in (?) "
	if e.MemberId != 0 {
		sql += " AND member_id = " + tools.IntToString(e.MemberId)
	} else if e.ThirdUserId != 0 {
		sql += " AND third_user_id = " + tools.IntToString(e.ThirdUserId)
	} else {
		return
	}

	if err = table.Exec(sql, id).Error; err != nil {
		return
	}
	Result = true
	return
}
